<template>
  <a-form
    class="w-3/4"
    :model="formRef"
    ref="form"
    size="large"
    @keyup.enter="handleLogin"
  >
    <a-form-item name="username" :rules="phoneRules">
      <a-input
        placeholder="用户名"
        size="large"
        v-model:value="formRef.username"
      ></a-input>
    </a-form-item>

    <a-form-item
      name="password"
      :rules="{
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      }"
    >
      <a-input-password
        placeholder="密码"
        size="large"
        v-model:value="formRef.password"
      ></a-input-password>
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 0 }">
      <a-button type="primary" w-full size="large" @click="handleLogin">
        登录
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { set_user_token } from '@/utils/storage';
import { userLogin } from '@/api/common';
import avatarPng from '@/assets/default_avatar.png';
import md5 from 'md5';
import crypto from 'crypto-js'
import { useUserStore } from '@/store/user';

const emits = defineEmits(['changeType']);

const formRef = reactive({
  username: '',
  password: ''
});

const form = ref();
const router = useRouter();
const route = useRoute();

const phoneRules = [
  {
    validator: (_rule, value) => {
      if (!value) return Promise.reject('请输入用户名');
      return Promise.resolve();
    },
  },
];

const userStore = useUserStore();
const handleLogin = () => {
  form.value.validate().then(async () => {
    let res = await userLogin({
      password: aesEncode(formRef.password),
      username: formRef.username
    })
    if (res.code == 'ok') {
      set_user_token(res.data.accessToken.accessToken);
      router.push({ path: '/' });
    }
  });
};

const userInfo = st.get('user_info');

onMounted(() => {
  let params =  new URLSearchParams(location.hash.split("login?")[1])
  formRef.username = params.get('userName') || ''
})
</script>
